const express = require("express");
// 配置跨域
const db = require("./db/index");
const cors = require("cors");
const app = express();

const http = require("http");
const socketIO = require("socket.io");
const server = http.createServer(app);
const io = socketIO(server, {
  allowEIO3: true,
  cors: {
    origin: "*", // 允许所有源
    methods: ["GET", "POST"], // 允许的 HTTP 方法
    credentials: true,
  },
});
module.exports = { app, server, io };

const handleSocketEvents = require("./controller/socketEvents");

handleSocketEvents(io, db);

// 解决跨域
app.use(cors());

server.listen(3200, () => {
  console.log("socket服务器正在监听 3200 端口");
});
// 引入路由
const userRouter = require("./router/user");
const userinfoRouter = require("./router/userinfo");
const addwallRouter = require("./router/wall");
const addWallCommentRouter = require("./router/wall_comment");
const addReqRouter = require("./router/request");
const addReqCommentRouter = require("./router/req_comment");
const addGoodsRouter = require("./router/goods");
const addBuysRouter = require("./router/buys");
const socketRouter = require("./router/socket");

//引入数据验证
const joi = require("joi");

// 配置文件
const config = require("./config/config");

// 配置优化res.send（）中间件
app.use((req, res, next) => {
  // status 0 成功 status 1 失败 默认为  1 方便处理失败
  res.cc = function (err, status = 1) {
    res.send({
      // 状态
      status,
      //   判断err是字符串还是错误消息 是字符串的话就直接输出
      message: err instanceof Error ? err.message : err,
    });
  };
  next();
});

// 配置表单解析数据中间件
// 配置解析表单数据中间件
app.use(express.urlencoded({ extended: false }));

// 要配置解析json中间件才能拿到数据
app.use(express.json());

// 配置 解析Token中间件
const expressJWT = require("express-jwt");

app.use(express.static("./static"));
// 解析token中间件

// 使用.unless({path:[/^\/api\//]})指定除了哪些接口不需要Token的身份认证
app.use(
  expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^\/api\//] })
);

// 用户登录注册router
app.use("/api", userRouter);
// 获取用户信息
app.use("/my", userinfoRouter);
app.use("/my", addwallRouter);
app.use("/my", addWallCommentRouter);
app.use("/my", addReqRouter);
app.use("/my", addReqCommentRouter);
app.use("/my", addGoodsRouter);
app.use("/my", addBuysRouter);
app.use("/my", socketRouter);
// 定义错误全局中间件
app.use((err, req, res, next) => {
  // 数据验证失败
  if (err instanceof joi.ValidationError) return res.cc(err);
  //   Token验证失败
  if (err.name === "UnauthorizedError") return res.cc("身份认证失败");
  // 未知错误
  res.cc(err);
});

app.get("/", (req, res) => {
  res.render("./static");
});

app.listen(3000, function () {
  console.log("api serve run at http://127.0.0.1:3000");
});
